<template>
  <div v-loading="pageLoading">
    <div v-if="!isPreview" :class="{'mobile-header':showMobilePage}" class="header-container">
      <ToolTip :content="title" style="max-width: 350px;" class="title"/>
      <div class="flex-1"/>
      <ListHeader />
    </div>
    <div :class="{'preview-container': isPreview, 'full-page': !isPreview, 'mobile-margin-top':showMobilePage && !isPreview}" class="page-container">
      <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
      <div v-if="formOptions && formOptions.config" class="page-content pb55">
        <el-form
          ref="formRef"
          :model="resultModel"
          :label-position="labelPosition"
          :label-width="labelWidth"
          :class="{'mobile-el-form': showMobilePage}"
          size="small"
          class="page-form"
        >
          <template v-for="(element, index) in formOptions.list">
            <div v-if="getElementShow(element)" :key="element.key">
              <el-row v-if="element.type === 'grid'" :gutter="4" :class="{'mb10': element.columns.length >= 3}" class="scroll" type="flex">
                <el-col v-for="gridElement in getAllActiveElement(element.columns)" :key="gridElement.key" :span="element.span || 12">
                  <FormMakeItem
                    :is-weibo-or-weixin="isWeiboOrWeixin"
                    :use-inner-upload="useInnerUpload"
                    :element="gridElement"
                    :form-options="formOptions"
                    :required-keys="requiredKeys"
                    :index="index"
                    @changeValueData="changeValueData"
                    @handleFormUserSelect="handleFormUserSelect"/>
                </el-col>
              </el-row>
              <FormMakeItem
                v-else
                :is-weibo-or-weixin="isWeiboOrWeixin"
                :use-inner-upload="useInnerUpload"
                :element="element"
                :index="index"
                :form-options="formOptions"
                :sub-form-obj="subFormObj"
                :required-keys="requiredKeys"
                @changeValueData="changeValueData"
                @selectHistory="selectHistory"
                @handleFormUserSelect="handleFormUserSelect" />
            </div>
          </template>
        </el-form>
      </div>
      <AuditProcess
        ref="auditProcess"
        :loading="loading"
        v-model="auditInfo"

        :old-audit-info="oldAuditInfo"
        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="submit(SUBMITTYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <fixed-pagination v-if="!isPreview">
        <div v-if="saveTime && !showMobilePage" class="save-info">
          <p>已自动保存当前信息</p>
          <p>{{ format(saveTime, 'YYYY/MM/DD HH:mm:ss') }}</p>
        </div>
        <div class="center">
          <el-button v-if="!remodifyId && !reapplyId" size="small" type="info" @click="submit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
          <el-button size="small" type="primary" @click="openDrawer()">发起审批</el-button>
          <el-button class="cancel-btn-style" size="small" @click="toBack">返回列表</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
/**
 * 发起自定义流程的审批
 */
import { mapState } from 'vuex';
// components
import ListHeader from '@/components/Common/header/listHeader';
import Title from '@/components/Title';
import FormMakeItem from '@/views/legal/process/components/formMake/components/FormMakeItem';
import explanation from '@/components/Common/explanation';
import AuditProcess from '@/components/Common/auditProcess';
// api
import { getApprovalTemplate, formSubmit, createApproval, approvalDetail, subformAutoFillIn, sensitiveWordsCheck } from '@/api/approvalModule';
import { getLeaderByUser } from '@/api/process';
import SetUserRelatePostDataMixin from '../mixins/setUserRelatePostData';
// tool
import { createLocalStorage } from '@/utils/storage';
import ElMessage from '@/utils/message';
import { SUBMITTYPE } from '@/utils/const/cost';
import { isNumberType, forEachFormOptions, mathFormula } from '@/utils/formMakeUtils.js';
import { initMathFormulaFunction } from '@/utils/formulaMath.js';
import { userChange } from '@/views/legal/process/components/formMake/utils/userField.js';
// import { testData } from './testData';
import { createAuditStructure } from '@/utils/aduitor';
import { isContained } from '@/utils/tools';
import { getMonthStr, pingIpAddress } from '@/utils';
import { INNER_ADDRESS } from '@/utils/const';
// import { getAllValidateField } from '../utils/index.js';
import { validateField, fieldPermissionJudge } from '../utils/filter.js';
import { showValidateMsg, handleRicheditorIndex, getImgList } from '../utils/index.js';
import processCreate from '@/mixins/processCreate';
import { decrypt } from '@/utils/secret';
import { showModal } from '@/utils/message';
import { format } from '@/filters/date';
import { CUSTOM_PROCESS_EVENT } from '@/utils/const/process';

// 缓存 60分钟
const ss = createLocalStorage({ expire: 60 * 60 });

export default {
  components: { Title, FormMakeItem, explanation, AuditProcess, ListHeader },
  mixins: [SetUserRelatePostDataMixin, processCreate],
  props: {
    isPreview: { // 是否预览
      type: Boolean, default: false
    }
  },
  provide() {
    return {
      fillContent: this.fillContent
    };
  },
  data() {
    return {
      resultModel: {},
      formOptions: {},
      moduleId: '', // 审批id
      detailId: '', // 这个审批单的详情ID
      SUBMITTYPE,
      isEdit: false,
      // 审批相关
      explanationObj: { // 审批说明
        content: '',
        styConfig: ''
      },
      pageLoading: false,
      loading: false,
      remodifyId: null, // 修改，审批流程不能修改
      reapplyId: null, // 重新申请
      auditInfo: { // 流程信息
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      title: '',
      eventData: {},
      requiredKeys: '', // 启用必填事件必填字段
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      processDetail: null,
      isAutoFillIn: false,
      newModuleId: '',
      subFormObj: {}, // 子表单对象
      saveTime: null, // 保存时间
      versionCreateTime: null, // 版本保存时间
      crmExtensionsUUID: '', // 浏览器插件返回的 uuid 用于对应生成的流程id
      insertData: null, // 浏览器插件返回
      noSaveCache: true,
      useInnerUpload: false // 是否使用内网上传
    };
  },
  computed: {
    isWeiboOrWeixin() {
      return this.title.includes('双微发文审批') || this.title.includes('双微发文审核');
    },
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'widgetTypes': state => state.formMake.widgetTypes,
      'fieldPermissions': state => state.formMake.fieldPermissions
    }),
    labelPosition() {
      if (this.formOptions.config.labelPosition === 'top') return 'top';
      return this.showMobilePage ? 'left' : (this.formOptions.config.labelPosition || 'right');
    },
    labelWidth() {
      const formOptions = this.formOptions;
      if (formOptions.config.labelPosition === 'top') return formOptions.config.labelWidth + 'px';
      return this.showMobilePage ? '100px' : formOptions.config.labelWidth + 'px';
    }
  },
  watch: {
    isWeiboOrWeixin(val) {
      if (val) {
        pingIpAddress(INNER_ADDRESS + '/common/ping').then(status => {
          this.useInnerUpload = status === true;
        }).catch(() => {
          this.useInnerUpload = false;
        });
      }
    }
  },
  created() {
    if (!this.isPreview) {
      // 插件传回来的id
      const _uuid = this.$route.query._uuid;
      if (_uuid) {
        try {
          const allinsertData = JSON.parse(localStorage.getItem('gc-extensions-insertData'));
          this.insertData = allinsertData[_uuid];
          console.log('new', this.insertData);
          window.postMessage({ type: 'gc-extensions', action: 'deleteInsertData', uuid: _uuid }, '*');
        } catch (error) {
          console.log(error);
        }
        if (!this.insertData) {
          // 旧版本插件兼容代码
          window.addEventListener('message', (e) => {
            if (e.data.type === 'gc-extensions') {
              const data = e.data;
              if (data.action === 'sendInsertDataToBackground' && data.data) {
                this.insertData = JSON.parse(data.data);
                console.log('old', this.insertData);
                window.postMessage({ type: 'gc-extensions', action: 'deleteInsertData', uuid: _uuid }, '*');
              }
            }
          }, false);
          window.postMessage({ type: 'gc-extensions', action: 'getInsertDataToBackground', uuid: _uuid }, '*');
        }
      }

      this.moduleId = Number(this.$route.params.moduleId);
      this.requiredKeys = this.$route.query.requiredKeys;
      const id = this.$route.query.id; // 详情id
      const remodifyId = this.$route.query.remodifyId; // 修改
      const reapplyId = this.$route.query.reapplyId; // 重新申请
      this.remodifyId = remodifyId;
      this.reapplyId = reapplyId;
      this.createNew = Number(this.$route.query.createNew) || 0;
      if (!id) {
        this.isEdit = false;
        this.getTemplate();
      } else {
        this.isEdit = true;
        this.detailId = id;
        this.getDetailData();
      }
    }
  },
  mounted() {
    if (!this.isPreview) {
      const _uuid = this.$route.query._uuid || null;
      this.getFormTimeOut = setTimeout(() => {
        if (!_uuid) {
          this.getFormData();
        }
      }, 500);
    }
  },
  beforeDestroy() {
    clearTimeout(this.getFormTimeOut);
    this.getFormTimeOut = null;
  },
  methods: {
    handleRicheditorIndex,
    format,
    fillContent(data, isFromLink) {
      if (data) {
        console.log(data);
        try {
          if (data.uuid) {
            this.crmExtensionsUUID = data.uuid;
          }
          if (data && ['weibo', 'weixin'].includes(data.type) && this.formOptions.list) {
            /**
             * 图片和视频单独回填，因为请求接口需要时间，如果图片太多会导致卡在页面太久，
             * 所以先提前回填不需要请求接口的
             */
            this.fillExtensionsImg(data);
            forEachFormOptions(this.formOptions.list, (item) => {
              if (data.type && item.name === '平台') {
                this.$set(item, 'value', data.type === 'weibo' ? '微博' : '微信');
              }
              if (data.accountName && item.name === '账号') {
                this.$set(item, 'value', data.accountName);
              }
              if (data.input && item.name.includes('发布内容')) {
                if (isFromLink) {
                  this.$set(item, 'value', '');
                }
                if (data.type === 'weixin' && !item.options.readonly && !item.options.createHide) {
                  window.postMessage({ type: 'RichEditor-setDangerouslyInsertHtml', data: data.input }, '*');
                } else {
                  this.$set(item, 'value', data.input);
                }
              }
              if (data.screenImg && item.name.includes('发布截图')) {
                this.$set(item, 'value', [{
                  time: new Date().getTime(),
                  url: data.screenImg,
                  name: '截图.png'
                }]);
              }
            });
          }
          // this.insertData = null;
        } catch (error) {
          console.log(error);
        }
      }
    },
    // 回填图片和视频
    async fillExtensionsImg(data) {
      const typeMap = {
        'weibo': 0,
        'weixin': 1
      };
      let imgs = [];
      if (data.imgList) {
        imgs = await getImgList(data.imgList, typeMap[data.type]) || [];
      }
      let videoList = [];
      if (data.videoList) {
        videoList = await getImgList(data.videoList, typeMap[data.type], true) || [];
      }
      if (videoList.length) {
        imgs = imgs.concat(videoList);
      }

      if (data.video) {
        const fileExtension = data.video.split('.').pop();
        imgs.push({
          url: data.video,
          name: `视频.${fileExtension || 'mp4'}`,
          time: new Date().getTime()
        });
      }
      if (imgs.length) {
        forEachFormOptions(this.formOptions.list, (item) => {
          if ((item.name.includes('发布图片') || item.name.includes('发布附件')) && imgs.length) {
            this.$set(item, 'value', imgs);
          }
        });
      }
    },
    setFormData() {
      const params = JSON.parse(JSON.stringify(this.formOptions));
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      params.auditInfo = this.auditInfo;
      params.moduleId = this.moduleId;
      params.explanation = this.explanationObj.content;
      params.styConfig = this.explanationObj.styConfig;
      if (this.reapplyId || !this.isEdit || this.createNew) {
        this.handelFormOptionsList(params.list, true, false);
        if (this.reapplyId) params.submitType = 3;
      } else {
        this.handelFormOptionsList(params.list, false, false);
        params.id = this.detailId;
      }
      params.newModuleId = this.newModuleId;
      params.versionCreateTime = this.versionCreateTime;
      if (this.$route.query.id) {
        params.detailId = this.$route.query.id;
      }
      this.handleModifyData(params);
      ss.set('customProcessForm', params);
      this.saveTime = new Date().getTime();
    },
    getFormData() {
      const data = ss.get('customProcessForm');

      if (data) {
        const id = Number(data.id || data.detailId);
        const detailId = Number(this.detailId);
        if (data && ((detailId && (id === detailId)) || (!detailId && (data.moduleId === this.moduleId)))) {
          if (this.versionCreateTime && (data.versionCreateTime !== this.versionCreateTime)) {
            ElMessage.warning('该审批表单已更新，缓存已自动清除！');
            this.removeCache();
            return;
          }
          showModal('请确认是否恢复上次所填数据？', '', { closeOnClickModal: false }, true).then(() => {
            this.noSaveCache = true;
            // 只有realValue有值时才需要对关联审批进行处理
            data.list.forEach(item => {
              if (item.type === 'associatedApproval' && item.value && item.realValue) {
                item.value = item.realValue;
              }
            });
            this.formOptions = {
              config: data.config,
              list: data.list
            };
            this.formOptions.event = _.cloneDeep(data.event || []);
            this.formOptions.notice = _.cloneDeep(data.notice || []);
            if (data.config) {
              const permissionsSetting = data.config.permissionsSetting || [];
              this.setFieldPermissionsToStore(permissionsSetting);
            }
            // 审批说明
            this.formOptions.moduleId = data.moduleId;
            this.explanationObj.content = data.explanation || '';
            this.explanationObj.styConfig = data.styConfig || '';
            this.newModuleId = data.newModuleId || '';
            this.postFollowerData = data.config.postFollowerData || {};
            // this.setDefault(data.list);
            this.subformAutoFillIn();
            this.mathFormula();
            this.$nextTick(() => {
              this.handleRicheditorIndex();
            });
            setTimeout(() => {
              this.removeCache();
            }, 1000);
          }).catch(() => {
            this.removeCache();
          });
        }
      }
    },
    subformAutoFillIn() {
      subformAutoFillIn({ workFlowId: this.moduleId }).then(res => {
        if (res.code === 200 && res.data) {
          const list = res.data.list;
          const tempSubForm = this.formOptions.list.filter(item => {
            return item.type === 'subform';
          });
          list.map(it => {
            if (it.type === 'subform') {
              const res = it.value;
              if (tempSubForm.length > 0) {
                tempSubForm[0].subform.forEach(subElement => {
                  if (res[0] && !Object.hasOwnProperty.call(res, subElement.key)) {
                    this.$set(res[0], subElement.key, it.value[0][subElement.key] || subElement.value);
                  }
                });
              }
              this.formOptions.list.forEach(item => {
                if (item.type === 'subform' && item.key === it.key && item.options.isAutoFillIn) {
                  item.value = res;
                }
              });
            }
          });
        }
      }).catch(err => {
        console.error(err);
      });
    },
    getDetailData() {
      approvalDetail({ id: this.detailId }).then(res => {
        if (res.data.auditInfo && !this.reapplyId && !this.createNew) {
          this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
          this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
          this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
        } else {
          // 审批说明
          this.explanationObj.content = res.data.explanation || '';
          this.explanationObj.styConfig = res.data.styConfig || '';
        }
        this.title = res.data.moduleName;
        this.formOptions = res.data;
        this.formOptions.moduleId = this.moduleId;
        this.formOptions.detailId = this.detailId;
        this.newModuleId = res.data.newModuleId || '';
        this.postFollowerData = this.formOptions.config.postFollowerData || {};
        this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        forEachFormOptions(this.formOptions.list, (i, subformKey, parentSubform) => {
          // 初始化解密
          // 再次发起（复制）需要把密码去掉
          if (i.options && i.options.isSecret) {
            if (parentSubform && parentSubform.value) {
              // 子表单 解密
              parentSubform.value.forEach(subform => {
                subform[i.key] = this.createNew ? '' : decrypt(subform[i.key], i);
              });
            } else {
              // 正常字段 解密
              i.value = this.createNew ? '' : decrypt(i.value, i);
            }
          }
        });
        this.handleEventSet();
        const permissionsSetting = this.formOptions.permissions || [];
        this.setFieldPermissionsToStore(permissionsSetting);
        this.mathFormula();
        this.$nextTick(() => {
          this.handleRicheditorIndex();
        });
      });
    },
    getMaxId(arr, key) {
      let maxId = arr[0][key];
      let maxIdObj = arr[0];
      for (let i = 1; i < arr.length; i++) {
        if (arr[i][key] > maxId) {
          maxId = arr[i][key];
          maxIdObj = arr[i];
        }
      }
      return maxIdObj;
    },
    eventFilter(list) {
      const result = _.cloneDeep(list);
      if (result.length) {
        this.formOptions.list.map(it => {
          const curArr = result.filter(item => item.target.includes(it.key));
          if (curArr.length && curArr.length > 1) {
            const curObj = this.getMaxId(curArr, 'operate');
            result.forEach(item => {
              const targets = item.target.split(',');
              targets.map(tg => {
                if (curObj.target.includes(tg) && item.operate !== curObj.operate) {
                  item.target = item.target.split(',').filter(i => i !== tg).join(',');
                }
              });
            });
          }
        });
      }
      return result;
    },
    handleEventSet() {
      const { currentNode } = this.formOptions.auditInfo;
      this.formOptions.auditInfo.process.map(it => {
        if (it.eventList && it.eventList.length && ((!currentNode && this.formOptions.processStatus) || it.id <= currentNode)) {
          const { event } = this.formOptions;
          const preEvent = event.filter(i => it.eventList.includes(i.id));
          const eventList = this.eventFilter(preEvent);
          const elementList = _.cloneDeep(this.formOptions.list);
          elementList.map(ele => {
            if (ele.type === 'grid' && ele.columns.length) {
              ele.columns.map(col => {
                if (col.list && col.list.length) {
                  col.list.map(j => {
                    elementList.push(j);
                  });
                }
              });
            }
          });
          eventList.length && eventList.forEach(e => {
            let targets = e.target.split(',');
            targets.map(v => {
              const element = elementList.find(it => it.key === v);
              const judge = fieldPermissionJudge(element, this.fieldPermissions);
              if (!judge) {
                targets = targets.filter(v => v !== element.key);
                e.target = targets.join(',');
              }
            });
          });
          if (eventList.length) {
            eventList.map(el => {
              if (el.target) {
                const targets = el.target.split(',');
                switch (el.operate) {
                  case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_HIDE:
                    targets.map(v => {
                      if (!this.eventData[v]) this.$set(this.eventData, v, {});
                      // this.eventData[v].hide = true; // 详情页隐藏
                      this.eventData[v].hideAfterId = it.id - 1;
                      if (this.eventData[v].showAfterId) delete this.eventData[v].showAfterId;
                      if (this.eventData[v].editAfterId) delete this.eventData[v].editAfterId;
                      if (this.eventData[v].requiredAfterId) delete this.eventData[v].requiredAfterId;
                      if (this.eventData[v].readOnlyAfterId) delete this.eventData[v].readOnlyAfterId;
                    });
                    break;
                  case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_DISPLAY:
                    targets.map(v => {
                      if (!this.eventData[v]) this.$set(this.eventData, v, {});
                      this.eventData[v].showAfterId = it.id - 1;
                      if (this.eventData[v].isEventEdit) delete this.eventData[v].isEventEdit;
                      if (this.eventData[v].hideAfterId) delete this.eventData[v].hideAfterId;
                      if (this.eventData[v].editAfterId) delete this.eventData[v].editAfterId;
                      if (this.eventData[v].requiredAfterId) delete this.eventData[v].requiredAfterId;
                      if (this.eventData[v].readOnlyAfterId) delete this.eventData[v].readOnlyAfterId;
                      const element = elementList.find(it => it.key === v);
                      if (element) {
                        this.eventData[v].hide = this.eventData[v].hide || this.validateField(element) !== null ? !this.validateField(element) : (element.options && element.options.detailHide);
                      }
                    });
                    break;
                  case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_ENABLE:
                    targets.map(v => {
                      if (!this.eventData[v]) this.$set(this.eventData, v, {});
                      // this.eventData[v].isEventEdit = true;
                      this.eventData[v].editAfterId = it.id - 1;
                      if (this.eventData[v].hideAfterId) delete this.eventData[v].hideAfterId;
                      if (this.eventData[v].showAfterId) delete this.eventData[v].showAfterId;
                      if (this.eventData[v].requiredAfterId) delete this.eventData[v].requiredAfterId;
                      if (this.eventData[v].readOnlyAfterId) delete this.eventData[v].readOnlyAfterId;
                    });
                    break;
                  case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_REQUIRED:
                    targets.map(v => {
                      if (!this.eventData[v]) this.$set(this.eventData, v, {});
                      this.eventData[v].hide = false;
                      this.eventData[v].requiredAfterId = it.id - 1;
                      this.eventData[v].editAfterId = it.id - 1;
                      if (this.eventData[v].hideAfterId) delete this.eventData[v].hideAfterId;
                      if (this.eventData[v].showAfterId) delete this.eventData[v].showAfterId;
                      if (this.eventData[v].readOnlyAfterId) delete this.eventData[v].readOnlyAfterId;
                    });
                    break;
                  case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_READ_ONLY:
                    targets.map(v => {
                      if (!this.eventData[v]) this.$set(this.eventData, v, {});
                      this.eventData[v].readOnlyAfterId = it.id - 1;
                      if (this.eventData[v].isEventEdit) delete this.eventData[v].isEventEdit;
                      if (this.eventData[v].hideAfterId) delete this.eventData[v].hideAfterId;
                      if (this.eventData[v].editAfterId) delete this.eventData[v].editAfterId;
                      if (this.eventData[v].showAfterId) delete this.eventData[v].showAfterId;
                      if (this.eventData[v].requiredAfterId) delete this.eventData[v].requiredAfterId;
                      const element = elementList.find(it => it.key === v);
                      if (element) {
                        this.eventData[v].hide = this.eventData[v].hide || this.validateField(element) !== null ? !this.validateField(element) : (element.options && element.options.detailHide);
                        forEachFormOptions(this.formOptions.list, item => {
                          if (item.key === v || item.linkFormKey === v) {
                            if (item.options.hasOwnProperty('readonly')) item.options.readonly = true;
                            if (item.options.hasOwnProperty('required')) item.options.required = false;
                          }
                        });
                      }
                    });
                    break;
                  // case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_HIDE_AFTER_APPROVE:
                  //   targets.map(v => {
                  //     if (!this.eventData[v]) this.$set(this.eventData, v, {});
                  //     const element = elementList.find(it => it.key === v);
                  //     const res = {
                  //       ...this.eventData[v],
                  //       hideAfterId: this.eventData[v].hideAfterId || it.id,
                  //       hide: this.eventData[v].hide || this.validateField(element) !== null ? !this.validateField(element) : (element.options && element.options.detailHide)
                  //     };
                  //     this.$set(this.eventData, v, { ...res });
                  //   });
                  //   break;
                  // case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_SHOW_AFTER_APPROVE:
                  //   targets.map(v => {
                  //     if (!this.eventData[v]) this.$set(this.eventData, v, {});
                  //     const element = elementList.find(it => it.key === v);
                  //     const res = {
                  //       ...this.eventData[v],
                  //       showAfterId: this.eventData[v].showAfterId || it.id,
                  //       hide: this.eventData[v].hide || this.validateField(element) !== null ? !this.validateField(element) : (element.options && element.options.detailHide)
                  //     };
                  //     this.$set(this.eventData, v, { ...res });
                  //   });
                  //   break;
                  // case CUSTOM_PROCESS_EVENT.TURN_ON_FIELD_ENABLE_AFTER_APPROVE:
                  //   targets.map(v => {
                  //     if (!this.eventData[v]) this.$set(this.eventData, v, {});
                  //     const element = elementList.find(it => it.key === v);
                  //     const res = {
                  //       editAfterId: this.eventData[v].editAfterId || it.id,
                  //       hide: this.eventData[v].hide || this.validateField(element) !== null ? !this.validateField(element) : (element.options && element.options.detailHide)
                  //     };
                  //     this.$set(this.eventData, v, { ...res });
                  //   });
                  //   break;
                }
              }
            });
          }
        }
      });
    },
    getTemplate() {
      this.pageLoading = true;
      getApprovalTemplate({ id: this.moduleId }).then(res => {
        this.pageLoading = false;
        if (res.code === 200 && res.data.formOptions) {
          this.formOptions = res.data.formOptions;
          this.title = res.data.baseOptions.name;
          if (res.data.advancedOptions) {
            const event = res.data.advancedOptions.event || [];
            const notice = res.data.advancedOptions.notice || [];
            const permissionsSetting = res.data.advancedOptions.permissions || [];
            this.setFieldPermissionsToStore(permissionsSetting);
            this.formOptions.event = _.cloneDeep(event);
            this.formOptions.notice = _.cloneDeep(notice);
          }
          // 审批说明
          this.formOptions.moduleId = res.data.processOptionsDetail.id || this.moduleId;
          this.explanationObj.content = res.data.processOptionsDetail.explanation || '';
          this.explanationObj.styConfig = res.data.processOptionsDetail.styConfig || '';
          this.newModuleId = res.data.processOptionsDetail.id || '';
          this.versionCreateTime = res.data.versionCreateTime;
          this.postFollowerData = this.formOptions.config.postFollowerData || {};
          this.setDefault(this.formOptions.list);
          this.subformAutoFillIn();
          this.mathFormula();
          this.$nextTick(() => {
            this.handleRicheditorIndex();
          });
          this.fillContent(this.insertData);
        }
      }).catch((err) => {
        this.pageLoading = false;
        console.log(err);
      });
    },
    selectHistory(data) {
      this.formOptions.list.forEach(it => {
        if (it.key === data.key) {
          // it.value = [data];
          it.value.forEach(ele => {
            if (ele._id === data.rowId) {
              ele = Object.assign(ele, data);
              ele._id = data.rowId;
            }
          });
        }
      });
    },
    // 保存当前用户所有不可读字段的判断结果
    setFieldPermissionsToStore(list) {
      const allFieldPermissions = [];
      if (Array.isArray(list) && list.length) {
        list.forEach(item => {
          const hasFieldPermission = this.getRowFieldPermission(item);
          hasFieldPermission && allFieldPermissions.push(...item.fieldPermissions.split(','));
        });
      }
      this.$store.dispatch('setFieldPermissions', [...new Set(allFieldPermissions)]);
    },
    // 判断当前用户是否有字段可读权限
    getRowFieldPermission(data) {
      if (!data.fieldPermissions) return false;
      if (data.isSelectAll) return true;
      let result = false;
      if (Array.isArray(data.members) && data.members.length) {
        result = data.members.some(member => member.id === this.userInfo.id);
      }
      if (!result && Array.isArray(this.userInfo.currentDeptIds) && data.deptList.split(',')) {
        result = data.deptList.split(',').some(deptId => this.userInfo.currentDeptIds.includes(Number(deptId)));
      }
      if (!result && data.postList) {
        result = data.postList.split(',').some(post => post === this.userInfo.post);
      }
      if (!result && data.roleGroup) {
        result = data.roleGroup.split(',').some(roleId => this.userInfo.roleGroupIds.includes(Number(roleId)));
      }
      return result;
    },
    async openDrawer() { // 流程弹窗
      this.setData();
      try {
        await this.validateTable();
        await this.validateSubForm();
        await this.validateAssociatedApproval();
        this.$refs.formRef.validate(async(valid) => {
          if (valid) {
            const sensitiveWordsCheck = await this.sensitiveWordsCheck();
            if (sensitiveWordsCheck) {
              this.getProcessDetail();
            }
          } else {
            ElMessage.error('请检查信息是否填写完整');
          }
        });
      } catch (error) {
        ElMessage.error(error);
      }
    },
    async submit(submitType = SUBMITTYPE.SUBMIT, senders = []) { // 1草稿 2保存提交 3重新提交
      this.modifySenders = senders;// 存到mixins
      const params = JSON.parse(JSON.stringify(this.formOptions));
      this.removePreview(params.list);
      params.submitType = submitType;
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      params.auditInfo = this.auditInfo;
      params.moduleId = this.moduleId;
      params.explanation = this.explanationObj.content;
      params.styConfig = this.explanationObj.styConfig;
      if (submitType === SUBMITTYPE.DRAFT) {
        const sensitiveWordsCheck = await this.sensitiveWordsCheck();
        if (!sensitiveWordsCheck) {
          return;
        }
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handelFormOptionsList(params.list, false);
        params.id = this.detailId;
        params.newModuleId = this.newModuleId;
        this.handleModifyData(params);
        this.add(params);
        return;
      }
      const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      this.$confirm(msg, '', {
        confirmButtonText: '确定', type: 'warning', showClose: false,
        center: true, iconClass: 'charge-icon', customClass: `del-message del-message-cancel${this.showMobilePage ? ' mobile-message' : ''}`
      }).then(() => {
        if (this.reapplyId || !this.isEdit || this.createNew) {
          this.handelFormOptionsList(params.list, true);
          if (this.reapplyId) params.submitType = 3;
        } else {
          this.handelFormOptionsList(params.list, false);
          params.id = this.detailId;
        }
        params.newModuleId = this.newModuleId;
        this.handleModifyData(params);
        this.add(params);
      });
    },
    add(params) {
      this.loading = true;
      createApproval(params).then(res => {
        this.removeCache();
        this.loading = false;
        if (res.code === 200) {
          this.setUUIDToProcess(res.data.processId);
          ElMessage.success(params.submitType === SUBMITTYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'approvalModuleDetail',
              params: { moduleId: this.moduleId },
              query: { id: res.data.id, processId: res.data.processId, isNew: true }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'approvalModuleDetail', params: { moduleId: this.moduleId }, query: { id: this.detailId, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    setUUIDToProcess(processId) {
      if (!this.crmExtensionsUUID) return;
      window.postMessage({ type: 'gc-extensions', action: 'sendUUIDToProcess', data: {
        tabId: this.crmExtensionsUUID,
        processId
      }}, '*');
    },
    // 监听所有人员选择组件变化
    handleFormUserSelect(data) {
      // 获取当前变化人员的职位映射
      const postArr = this.postFollowerData[data.key];
      postArr && this.setCurrUserPostToPostField(data, postArr);
      this.mathFormula();
    },
    /**
     * 流程相关
     */
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    setFormSubmitParams() {
      const data = _.cloneDeep(this.formOptions);
      // 关联审批类型需要调整提交的格式
      forEachFormOptions(data.list, (el, subformKey, parentSubform) => {
        if (el.type === 'associatedApproval' && Array.isArray(el.value)) {
          if (el.value.length) {
            el.value = el.value.map(item => item.id).join();
          } else {
            el.value = '';
          }
        }
        if (el.type === 'input' && el.options.isShowPercentage) {
          if (el.value) el.value = el.value / 100;
          if (parentSubform && parentSubform.value) {
            // 子表单字段处理
            parentSubform.value.forEach(val => {
              if (val[el.key]) val[el.key] = val[el.key] / 100;
            });
          }
        }
      });
      data.moduleId = this.moduleId;
      data.newModuleId = this.newModuleId;
      return data;
    },
    sensitiveWordsCheck() {
      return new Promise((resolve, reject) => {
        const { list } = this.setFormSubmitParams();
        const fitList = [];
        forEachFormOptions(list, (element) => {
          const types = ['textarea', 'input', 'richEditor', 'subform'];
          if (types.includes(element.type)) {
            fitList.push(element);
          }
        }, { notForEachSubform: true });
        sensitiveWordsCheck({ list: fitList }).then(res => {
          if (res.code === 200) {
            resolve(true);
          }
        }).catch(err => {
          if (err.code === 504 && err.data) {
            reject(false);
            showValidateMsg(err.data);
          }
          if (err.code === 608 && err.data) {
            showValidateMsg(err.data, { showCancelButton: true, catchReject: true, customClass: 'del-message-cancel del-message' }, () => {
              resolve(true);
            }, () => {
              reject(false);
            });
          }
        });
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const data = this.setFormSubmitParams();
      // const errorMsg = validateEntireForm(data, true);
      // if (errorMsg && errorMsg.length) {
      //   showValidateMsg(errorMsg);
      //   return;
      // }
      formSubmit(data).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, this.userInfo);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        console.log(err);
        this.loading = false;
        if (err.code === 504 && err.data) {
          showValidateMsg(err.data);
        }
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    /**
     * 设置默认值
     */
    setPreviewOption(formOptions) {
      this.formOptions = formOptions;
      this.setDefault(this.formOptions.list);
      this.postFollowerData = this.formOptions.config.postFollowerData || {};
      setTimeout(() => {
        this.handleRicheditorIndex();
        initMathFormulaFunction(this.formOptions);
      }, 0);
    },
    setDefault(formOptionsList) {
      if (formOptionsList) {
        const formulaHighMode = []; // 收集哪些字段是被高级公式字段引用的
        forEachFormOptions(formOptionsList, async(i, subformKey) => {
          if (i.type === 'date') {
            const isDefaultNowTime = i.options.isDefaultNowTime;
            const currentMonth = new Date().valueOf();
            const { entryTime, dimissionTime } = this.userInfo;
            const userEntryTime = entryTime && entryTime * 1000 || null;
            const userResignTime = dimissionTime && dimissionTime * 1000 || null;
            const lastMonth = getMonthStr(-1);
            const nextMonth = getMonthStr(1);
            const dateMap = ['', currentMonth, userEntryTime, userResignTime, lastMonth, nextMonth];
            i.value = dateMap[isDefaultNowTime];
          } else if (i.type === 'department') {
            i.value = this.setDepartmentDefault(i);
          } else if (i.type === 'user') {
            const user = await this.setUserDefault(i);
            if (user) i.value = user;
            const cloneItem = _.cloneDeep(i);
            cloneItem._postValue = { ...i.value };
            this.handleFormUserSelect(cloneItem);
          } else if (i.type === 'subform') {
            this.setDefaultSubform(i);
          } else if (i.type === 'checkbox' && !Array.isArray(i.value)) {
            i.value = [];
          } else if (i.type === 'upAttachment' && !Array.isArray(i.value)) {
            i.value = [];
          } else if (i.type === 'post' && i.options.defaultPost === 1) {
            // 职位跟随 创建人职位
            const { post } = this.userInfo;
            const currUserPost = { id: post, name: post };
            this.$set(i, 'value', i.options.isMultiple ? [currUserPost] : currUserPost);
          }
          // 使子表单里面的数字字段的值变为 number 类型
          if (i.type === 'subform' && i.value) {
            const numberKeys = i.subform.map(i => {
              if (isNumberType(i) || (i.type === 'date' && !i.options.isRange)) return i.key;
              return null;
            }).filter(i => !!i);
            i.value.forEach(i => {
              numberKeys.forEach(numKey => {
                if (i[numKey]) i[numKey] = Number(i[numKey]);
              });
            });
          }
          if (i.type === 'user') {
            // 如果有的话，触发关联字段
            this.userChange(i);
          }
          if (i.type === 'formulaInput' && i.options.modeType && i.options.formulaString) {
            const widget = /\$_widget_(.+?)_end\$/g;
            i.options.formulaString.replace(widget, function(math, key) {
              if (!formulaHighMode.includes(key)) {
                formulaHighMode.push(key);
              }
              const splitKey = key.split('_');
              if (splitKey.length >= 3) {
                const k = `${splitKey[0]}_${splitKey[1]}`;
                if (!formulaHighMode.includes(k)) {
                  formulaHighMode.push(k);
                }
              }
            });
          }
        });
        this.formOptions.config.formulaHighMode = formulaHighMode;
      }
    },
    removePreview(list) {
      forEachFormOptions(list, (i) => {
        if (i.type === 'upAttachment' && i.value) {
          i.value = i.value.filter(item => item.type !== 'preview');
        }
      });
    },
    handelFormOptionsList(formOptionsList, isCreate, requireDeal = true) {
      forEachFormOptions(formOptionsList, (i, subformKey, parentSubform) => {
        if ((isNumberType(i)) && i.value) {
          i.value = Number(i.value);
        }
        if (i.type === 'createUser' && isCreate) {
          i.value = { id: this.userInfo.id, userName: this.userInfo.userName };
        }
        if (requireDeal && i.type === 'associatedApproval' && Array.isArray(i.value)) {
          if (i.value.length) {
            i.value = i.value.map(item => item.id).join();
          } else {
            i.value = '';
          }
        }
        if (i.type === 'input' && i.options.isShowPercentage) {
          if (i.value) i.value = i.value / 100;
          if (parentSubform && parentSubform.value) {
            // 子表单字段处理
            parentSubform.value.forEach(val => {
              if (val[i.key]) val[i.key] = val[i.key] / 100;
            });
          }
        }
      });
    },
    setData() {
      const list = this.formOptions.list;
      list.forEach(i => {
        if (i.key) this.resultModel[i.key] = i.value;
      });
    },
    validateTable() {
      return new Promise((resolve, reject) => {
        const list = this.formOptions.list;
        let isError = false;
        list.forEach(i => {
          if ((i.type === 'subform' || i.type === 'linkForm') &&
            (this.getElementShow(i) && i.options.required)) {
            if (!i.value || i.value.length === 0) {
              isError = `${i.name}不能为空`;
            }
          }
        });
        if (isError) {
          reject(isError);
        } else {
          resolve(true);
        }
      });
    },
    validateSubForm() {
      return new Promise((resolve, reject) => {
        const list = this.formOptions.list;
        let isError = false;
        let name = '';
        let errorkey = '';
        list.forEach(k => {
          if (k.type === 'subform' && !k.options.isCard && this.getElementShow(k) && k.value && k.value.length) {
            k.subform.forEach(i => {
              if (!isError && this.getElementShow(i) && i.options.required && !i.options.disabled) {
                k.value.forEach(j => {
                  const isNull = j[i.key] === null || j[i.key] === undefined;
                  const isArray = Array.isArray(j[i.key]) && j[i.key].length === 0;
                  const isObject = typeof j[i.key] === 'object' && !Array.isArray(j[i.key]) && JSON.stringify(j[i.key]) === '{}';
                  const isStr = typeof j[i.key] !== 'object' && !j[i.key] && j[i.key] !== 0;
                  if (isNull || isStr || isArray || isObject) {
                    isError = true;
                    name = k.name;
                    errorkey = i.name;
                  }
                });
              }
            });
          }
        });
        if (isError) {
          reject(`${name}中的${errorkey}为必填`);
        } else {
          resolve(true);
        }
      });
    },
    toBack() {
      this.$router.push({
        name: 'approvalList',
        params: { id: this.moduleId }
      });
    },
    validateAssociatedApproval() {
      return new Promise((resolve, reject) => {
        const list = this.formOptions.list;
        let isError = false;
        list.forEach(i => {
          if ((i.type === 'associatedApproval') && this.getElementShow(i) && i.options.required) {
            if (!i.value || i.value.length === 0) {
              isError = `请添加${i.name}`;
            }
          }
        });
        if (isError) {
          reject(isError);
        } else {
          resolve(true);
        }
      });
    },
    userChange(changeElement) {
      const that = this;
      userChange(changeElement, this.formOptions, {
        userInfo: this.userInfo,
        handleFormUserSelect: (element, value) => {
          const cloneElement = _.cloneDeep(element);
          if (value && !Array.isArray(value)) cloneElement['_post'] = value && value.post || null;
          cloneElement._postValue = { ...value };
          that.handleFormUserSelect(cloneElement);
        }
      });
    },
    async getLeaderByUserApi(element) {
      const type = element.options.defaultValue - 2;
      const ids = `${this.userInfo.id}`;
      if (!ids) { return []; }
      const result = await getLeaderByUser({ ids, type }).then(res => {
        if (res.code === 200) {
          return res.data;
        }
      }).catch(err => {
        console.error(err.message);
      });
      return result;
    },
    // 设置默认用户
    async setUserDefault(item) {
      const multiple = item.options.multiple;
      const defaultValue = item.options.defaultValue;
      // const userSelectValue = item.options.userSelectValue;
      if (defaultValue === 1) {
        const user = { id: this.userInfo.id, userName: this.userInfo.userName, post: this.userInfo.post };
        return multiple ? [user] : user;
      } else if (defaultValue > 1 && defaultValue < 5) {
        // 只有不需要关联其他字段的人员字段会请求
        const result = await this.getLeaderByUserApi(item);
        return multiple ? result : result[0];
      }
      return multiple ? [] : '';
    },
    // 设置默认部门
    setDepartmentDefault(item) {
      const multiple = item.options.multiple;
      const defaultValue = item.options.defaultValue;
      if (this.userInfo) {
        if (defaultValue === 0) {
        // 回填当前用户一级部门
          if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
            const dept = this.userInfo.deptName[0];
            return multiple ? [{ id: dept.id, name: dept.name }] : { id: dept.id, name: dept.name };
          }
        } else if (defaultValue === 1) {
        // 回填当前用户第一个当前部门
          if (this.userInfo.subDepartment && this.userInfo.subDepartment.length > 0 && this.userInfo.subDepartment[0].id) {
            const dept = this.userInfo.subDepartment[0];
            return multiple ? [{ id: dept.id, name: dept.name }] : { id: dept.id, name: dept.name };
          } else if (this.userInfo.deptName && this.userInfo.deptName.length) {
            const dept = this.userInfo.deptName[0];
            return multiple ? [{ id: dept.id, name: dept.name }] : { id: dept.id, name: dept.name };
          }
        }
      }
      return multiple ? [] : '';
    },
    setDefaultSubform(i) {
      this.subFormObj = i;
    },
    // 收集普通人员选择字段
    getUserSelectData(key) {
      let arr = [];
      forEachFormOptions(this.formOptions.list, (element, subformKey, parentSubform) => {
        if (element.key === key) {
          if (!element.isSubTable) {
            // 非子表单字段，直接去该字段的value
            element.options.multiple ? (arr = element.value) : arr.push(element.value);
          } else {
            // 子表单字段，需要取其父节点的value
            // parentSubform.value.
          }
        }
      });
      return arr;
    },
    // 收集子表单人员选择字段
    getSubUserSelectData(key) {
      let arr = [];
      if (this.formOptions.list.length) {
        this.formOptions.list.map(it => {
          if (it.type === 'subform' && it.subform.length) {
            it.subform.map(item => {
              if (item.type === 'user' && item.value && item.key === key) {
                item.options.multiple ? (arr = item.value) : arr.push(item.value);
              }
            });
          }
        });
      }
      return arr;
    },
    mathFormula() {
      let hasFormulaInput = false;
      let hasHightFormulaInput = false;
      forEachFormOptions(this.formOptions.list, (el) => {
        if (el.type === 'formulaInput' && !el.options.modeType) {
          hasFormulaInput = true;
        } else if (el.type === 'formulaInput' && el.options.modeType) {
          hasHightFormulaInput = true;
        }
      });
      if (hasFormulaInput) {
        this.$nextTick(() => {
          mathFormula(this.formOptions, {}, false, true);
        });
      }
      if (hasHightFormulaInput) {
        this.$nextTick(() => {
          initMathFormulaFunction(this.formOptions);
        });
      }
    },
    changeValueData(el) {
      if (!this.noSaveCache) {
        this.saveCache();
      }
      this.setCacheFlag();
    },
    setCacheFlag: _.debounce(function() {
      this.noSaveCache = false;
    }, 3000),
    saveCache: _.throttle(function() {
      this.setFormData();
    }, 3000),
    removeCache() {
      ss.remove('customProcessForm');
      this.saveTime = null;
    },
    getAllActiveElement(list = []) {
      const elementArr = [];
      let maxColLength = 0;
      list && list.forEach(colData => {
        maxColLength = Math.max(maxColLength, colData.list.length || 0);
      });
      for (let colIndex = 0; colIndex < maxColLength; colIndex++) {
        list.forEach(colData => {
          if (Array.isArray(colData.list) && colData.list.length > colIndex && this.getElementShow(colData.list[colIndex])) {
            elementArr.push(colData.list[colIndex]);
          }
        });
      }
      return elementArr;
    },
    getElementShow(element) {
      // 权重：字段权限＞流程事件＞字段显隐条件＞字段属性
      if (!fieldPermissionJudge(element, this.fieldPermissions)) {
        return false;
      }
      if (this.detailId && !_.isEmpty(this.formOptions) && this.formOptions.auditInfo && this.formOptions.auditInfo.currentNode && this.eventData[element.key]) {
        const { currentNode } = this.formOptions.auditInfo;
        const eventData = this.eventData;

        // 显示
        if (eventData[element.key].hideAfterId && currentNode > eventData[element.key].hideAfterId) {
          return false;
        } else if ((eventData[element.key].editAfterId && currentNode > eventData[element.key].editAfterId) ||
          (eventData[element.key].showAfterId && currentNode > eventData[element.key].showAfterId) ||
          (eventData[element.key].readOnlyAfterId && currentNode > eventData[element.key].readOnlyAfterId) ||
          !eventData[element.key].hide) {
          return true;
        }
      }
      const validateResult = this.validateField(element);
      if (validateResult !== null) {
        return validateResult;
      }
      return (!element.options || !element.options.createHide);
    },
    // 判断组件是否可以展示
    validateField(element) {
      // 权重：字段权限＞流程事件＞字段显隐条件＞字段属性
      return validateField(element, this.formOptions);
    }
  }
};
</script>

<style lang="scss" scoped>
.mobile-header {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1001;
  width: 100%;
  background-color: #406EFF !important;
  .mobile-text {
    color: #fff !important;
  }
  .title {
    margin-left: 40px;
    color: #fff !important;
  }
}
.mobile-margin-top {
  margin-top: 64px !important;
}
.page-container {
  background-color: #fff;
  margin: 16px;
  &::v-deep {
    .el-form-item .richeditor{
      img, video {
        border-radius: 8px !important;
      }
      video {
        max-width: 300px;
        height: auto !important;
      }
      a {
        background-color: transparent !important;
        color: #406EFF !important;
        word-break: break-word;
      }
      ul, ol {
        margin: 0;
        padding-inline-start: 20px;
      }
      p {
        margin: 0;
        line-height: 1.5;
        text-align: left;
        overflow-wrap: break-word;
        word-break: break-word;
      }
      blockquote {
        background-color: #f5f2f0;
        border-left: 8px solid #b4d5ff;
        display: block;
        font-size: 100%;
        line-height: 1.5;
        margin: 10px 0 16px;
        padding: 10px;
      }
      table {
        border-collapse: collapse;
        padding: 0;
        border: 1px solid #ccc;
        border-radius: 3px;
        margin-bottom: 6px;
        tbody > tr:first-child {
          background-color: #eee;
        }
        th, td {
          border-right: 1px solid #ccc;
          border-top: 1px solid #ccc;
        }
        td:last-child, th:last-child {
          border-right: none;
        }
      }
    }
  }
}
.full-page {
  min-height: calc(100vh - 80px);
}
.page-content {
  padding: 16px 24px 24px;
  &.pb55 {
    padding-bottom: 65px;
  }
}
.preview-container {
  margin: 0;
}
.header-container {
  display: flex;
  align-items: center;
  width: 100%;
  background-color: #fff;
  padding-right: 16px;
  padding-left: 16px;
  height: 48px;
  .title {
    font-size: 16px;
    line-height: 1.5;
    font-family: PingFang SC;
    color: #333333;
  }
  .flex-1 {
    flex: 1;
  }
}
.mb10 {
  margin-bottom: 10px;
}
.scroll {
  flex-wrap: wrap;
  @include scrollBar($x: auto, $y: hidden);
}
.save-info {
  width: 132px;
  font-size: 12px;
  color: #999;
  p {
    margin: 0;
    white-space: nowrap;
  }
}
</style>
